﻿using System;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model._Admin;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using HengTong.Model.Db.Hr;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Wtm.Models;
using UUIDNext;


namespace HengTong.ViewModel.Person.SysPersonVms
{
    public partial class SysPersonVm : BaseCRUDVM<SysPerson>
    {
        public SysPersonVm()
        {
            SetInclude(x => x.Org);
            SetInclude(x => x.Group);
            SetInclude(x => x.JobPosition);
            SetInclude(x => x.PersonEducations);
            SetInclude(x => x.PersonFamilies);
            SetInclude(x => x.PersonWorks);
            SetInclude(x => x.PersonTrainExams);
            SetInclude(x => x.PersonMedicals);
            SetInclude(x => x.PersonResumes);
            SetInclude(x => x.PersonContracts);
        }

        protected override void InitVM()
        {
        }

        public override async Task DoAddAsync()
        {
            // 判断工号是否为空
            if (string.IsNullOrEmpty(Entity.StaffNo))
            {
                MSD.AddModelError("Entity.StaffNo", "工号不能为空");
                return;
            }

            // 判断身份证号是否为空
            if (string.IsNullOrEmpty(Entity.IdCardNo))
            {
                MSD.AddModelError("Entity.IdCardNo", "身份证号不能为空");
                return;
            }

            // 验证工号是否重复
            if (!string.IsNullOrEmpty(Entity.StaffNo))
            {
                var existingStaffNo = await DC.Set<SysPerson>()
                    .AsNoTracking()
                    .AnyAsync(x => x.StaffNo == Entity.StaffNo);
                if (existingStaffNo)
                {
                    MSD.AddModelError("Entity.StaffNo", "工号已存在，请使用其他工号");
                    return;
                }
            }

            // 验证手机号是否重复
            if (!string.IsNullOrEmpty(Entity.Phone))
            {
                var existingPhone = await DC.Set<SysPerson>()
                    .AsNoTracking()
                    .AnyAsync(x => x.Phone == Entity.Phone);
                if (existingPhone)
                {
                    MSD.AddModelError("Entity.Phone", "手机号已存在，请使用其他手机号");
                    return;
                }
            }

            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Entity.StaffNo;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            // 判断工号是否为空
            if (string.IsNullOrEmpty(Entity.StaffNo))
            {
                MSD.AddModelError("Entity.StaffNo", "工号不能为空");
                return;
            }

            // 判断身份证号是否为空
            if (string.IsNullOrEmpty(Entity.IdCardNo))
            {
                MSD.AddModelError("Entity.IdCardNo", "身份证号不能为空");
                return;
            }

            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Entity.StaffNo;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }

            // 开启事务
            var transaction = await DC.Database.BeginTransactionAsync();
            try
            {
                // 判断当前人员档案是否存在系统用户
                if (DC.Set<FrameworkUser>().Any(x => x.ITCode == Entity.StaffNo))
                {
                    // 如果存在，判断手机号和手机号是否一致，不一致则更新
                    var user = await DC.Set<FrameworkUser>().FirstOrDefaultAsync(x => x.ITCode == Entity.StaffNo);
                    if (Entity.Phone != user.CellPhone || Entity.GroupId != user.GroupId)
                    {
                        /*await DC.Set<FrameworkUser>().Where(x => x.ITCode == Entity.StaffNo)
                            .ExecuteUpdateAsync(x => x.SetProperty(y => y.CellPhone, Entity.Phone)
                                .SetProperty(y => y.GroupId, Entity.GroupId));*/
                        await DC.Set<FrameworkUser>().Where(x => x.ITCode == Entity.StaffNo)
                            .ExecuteUpdateAsync(x => x.SetProperty(y => y.CellPhone, Entity.Phone));
                        await DC.SaveChangesAsync();
                    }
                }


                await base.DoEditAsync(updateAllFields);
                // 提交事务
                await transaction.CommitAsync();
            }
            catch (Exception e)
            {
                // 回滚事务
                await transaction.RollbackAsync();
                MSD.AddModelError(" ", $"编辑操作异常: {e.Message}");
            }
            finally
            {
                // 释放事务
                await transaction.DisposeAsync();
            }
        }

        public async Task ApproveAsync(bool upAllFields = false)
        {
            DC = Wtm.CreateDC();
            var transaction = DC.BeginTransaction();
            try
            {
                if (Entity is IFlow flow)
                {
                    flow.Approver = Wtm.LoginUserInfo?.ITCode;
                    flow.ApprovalTime = DateTime.Now;
                }

                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    await ContinueWorkflowAsync(ActionName, Remark);
                    await transaction.CommitAsync();
                }
                else
                {
                    await transaction.RollbackAsync();
                }
            }
            catch (Exception e)
            {
                // 回滚事务
                await transaction.RollbackAsync();
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
            finally
            {
                await transaction.DisposeAsync();
            }
        }
    }
}